from  selenium import webdriver
from  selenium.webdriver.chrome.service import Service
from  selenium.webdriver.common.by import By
from  time import  sleep
service = Service("d:/chromedriver/chromedriver")
driver = webdriver.Chrome(service=service)
url = 'https://www.shanghai.gov.cn/'
driver.get(url)
sleep(3)  #等待几秒让页面加载完成
#匹配完整文本
element = driver.find_element(By.XPATH,'//p[text()="海纳百川 · 追求卓越 · 开明睿智 · 大气谦和"]')
print(f"{element.get_attribute('outerHTML')}")
#使用contains匹配部分文本
ele = driver.find_element(By.XPATH,'//p[contains(text(),"海纳百川 ")]')
print(f"{ele.get_attribute('outerHTML')}")
elements = driver.find_element(By.CSS_SELECTOR, 'p')
elements = [e for e in  elements if e.text == '海纳百川 · 追求卓越 · 开明睿智 · 大气谦和']
for index,element in enumerate(elements):
    print(f"元素{index+1}:{element.get_attribute('outerHTML')}")

todays = driver.find_element(By.CSS_SELECTOR, "today")
print("通过类名查找元素，class='today',元素的个数=", len(todays))
for i,element in enumerate(todays,1):
    print(f"元素{i}:{element.get_attribute('outerHTML')}")

res = driver.find_element(By.TAG_NAME, 'h2')
print("res:", len(res))
for i,element in enumerate(res,1):
    print(f"元素{i}:{element.get_attribute('outerHTML')}")
print("------------")

#通过xpath
#通过链接文本定位
res = driver.find_element(By.LINK_TEXT,'上海公安局')
for i, element in enumerate(res, 1):
    print(f"元素{i}:{element.get_attribute('outerHTML')}")

#通过部分链接文本匹配
res = driver.find_element(By.PARTIAL_LINK_TEXT,'公安局')
for i, element in enumerate(res, 1):
    print(f"元素{i}:{element.get_attribute('outerHTML')}")

sleep(3)
driver.quit()